//
//  PopoverAnimator.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/15.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit

class PopoverAnimator: NSObject,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
   
    // 是否正在展现的状态
    var isPresentation = false
    
    // 展现的frame  
    var presentedFrame = CGRectZero
    
    /// 返回控制 modal 管理的控制器
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController!, sourceViewController source: UIViewController) -> UIPresentationController? {
        let popover = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
        popover.presentedFrame = presentedFrame
        
        return popover
    }
    
    // 返回提供modal动画展现对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresentation = true
        return self
    }
    
    // 返回提供dismiss动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresentation = false
        return self
    }
    
    // 
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.5
    }
    
    /// 主动提供转场的动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        if isPresentation {
            // 获取目标视图
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            // 将目标控制器添加到容器视图
            transitionContext.containerView().addSubview(toView)
            
            // 动画方法,设置动画的初始形变
            toView.transform = CGAffineTransformMakeScale(1, 0)
            // 设置layer的锚点
            toView.layer.anchorPoint = CGPointMake(0.5, 0)
            // 设置动画
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5, options: nil, animations: { () -> Void in
                toView.transform = CGAffineTransformMakeScale(1, 1)
            }, completion: { _ in
                transitionContext.completeTransition(true)
            })
            
        }else{
            // 获得
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            
            // 将modal出来的视图 从容器视图中删除
            fromView.removeFromSuperview()
            
            // 告诉控制器  动画完成
            transitionContext.completeTransition(true)
        }
    }
    
}
